<template>
  <div id="psi">
    <div class="row row-1"></div>
    <div class="row row-2">
      <div class="col col-1">
        <div class="row row-1">
          <div class="declare">
            <p class="ellipsis">污染地图</p>
          </div>
        </div>
        <div class="row row-2">
          <div id="leaflet" class="leaflet"></div>
        </div>
      </div>
      <div class="col col-2">
        <div class="row row-1"></div>
        <div class="row row-2">
          <div class="row row-1">
            <div class="col col-1">
              <p class="ellipsis">污染源列表</p>
            </div>
            <div class="col col-2">
              <div class="row row-1">
                <div class="row">
                  <div class="col col-1">
                    <input
                      type="text"
                      maxlength="50"
                      v-model.trim="searchCondition"
                    />
                  </div>
                  <div class="col col-2">
                    <div class="button" @click="searchFunc()"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="row row-2">
            <div class="row">
              <vue-scroll :ops="ops">
                <div
                  v-for="item in taskArray"
                  :key="item.id"
                  :class="taskId === item.id ? 'row active' : 'row'"
                  @click="taskSelected(item.id)"
                >
                  <div class="row row-1">
                    <div class="col col-1">
                      <div class="table">
                        <div class="cell">
                          <p>
                            <span>{{ item.content }}</span>
                          </p>
                        </div>
                      </div>
                    </div>
                    <div class="col col-2">
                      <div class="row">
                        <div class="col col-1">
                          <p :class="item.step === 1 ? 'new' : 'processed'">
                            {{ formatterTaskStep(item.step) }}
                          </p>
                        </div>
                        <div class="col col-2">
                          <p>{{ item.distance }}米</p>
                        </div>
                        <div class="col col-3">
                          <p>{{ item.countrySpot }}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="row row-2">
                    <div class="col col-1">
                      <p>{{ item.address }}</p>
                    </div>
                    <div class="col col-2">
                      <p>{{ item.updatetime }}</p>
                    </div>
                  </div>
                </div>
              </vue-scroll>
            </div>
          </div>
        </div>
      </div>
      <div class="col col-3">
        <div class="row row-1">
          <div class="declare">
            <p class="ellipsis">污染源详情</p>
          </div>
        </div>
        <div class="row row-2">
          <div class="col col-1">
            <div class="row row-1">
              <div class="row row-1">
                <p>{{ taskData.content }}</p>
              </div>
              <div class="row row-2">
                <div class="row row-1">
                  <p>{{ taskData.address }}</p>
                </div>
                <div class="row row-2">
                  <p>{{ taskData.updatetime }}</p>
                </div>
              </div>
            </div>
            <div class="row row-2">
              <div class="row row-1">
                <p>污染类型：{{ formatterTaskType(taskData.contaminated) }}</p>
              </div>
              <div class="row row-2">
                <p>国控点：{{ taskData.countrySpot }}</p>
              </div>
              <div class="row row-3">
                <p>状态：{{ formatterTaskStep(taskData.step) }}</p>
              </div>
              <div class="row row-4">
                <p>范围：{{ formatterDistance(taskData) }}</p>
              </div>
              <div class="row row-5">
                <p>
                  位置：{{
                    utils.validateIsNotEmpty(taskData)
                      ? "距" + taskData.countrySpot + taskData.distance + "米"
                      : ""
                  }}
                </p>
              </div>
              <div class="row row-6">
                <p>上报人：{{ taskData.userName }}</p>
              </div>
            </div>
          </div>
          <div class="col col-2">
            <div class="row row-1">
              <p>整改前</p>
            </div>
            <div class="row row-2">
              <div id="psi-swiper-before" class="swiper-container">
                <div class="swiper-wrapper">
                  <div
                    class="swiper-slide"
                    v-for="item in beforeTaskImageArray"
                    :key="item.id"
                  >
                    <div class="table">
                      <div class="cell">
                        <img :src="item.path" />
                      </div>
                    </div>
                  </div>
                  <div
                    class="swiper-slide"
                    v-for="item in beforeTaskVideoArray"
                    :key="item.id"
                  >
                    <video
                      class="psi-video"
                      controls
                      preload="auto"
                      width="320"
                      height="180"
                      poster=""
                      data-setup="{}"
                    >
                      <source :src="item.path" type="video/mp4" />
                    </video>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col col-3">
            <div class="row row-1">
              <p>整改后</p>
            </div>
            <div class="row row-2">
              <div id="psi-swiper-after" class="swiper-container">
                <div class="swiper-wrapper">
                  <div
                    class="swiper-slide"
                    v-for="item in afterTaskImageArray"
                    :key="item.id"
                  >
                    <div class="table">
                      <div class="cell">
                        <img :src="item.path" />
                      </div>
                    </div>
                  </div>
                  <div
                    class="swiper-slide"
                    v-for="item in afterTaskVideoArray"
                    :key="item.id"
                  >
                    <video
                      class="psi-video"
                      controls
                      preload="auto"
                      poster=""
                      data-setup="{}"
                    >
                      <source :src="item.path" type="video/mp4" />
                    </video>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import L from "leaflet";
import "swiper/css/swiper.css";
import swiper from "swiper";
import "plyr/dist/plyr.css";
import plyr from "plyr";
import stateStationIcon from "../../assets/img/20200413102959.png";
import {
  getCityDistrict,
  getStateStationRealtime,
  getNewTaskList,
  getTaskTypeList
} from "../../axios/api";
import { getNewTaskPopupTemplate } from "../../utils/template";

export default {
  data() {
    return {
      ops: {
        bar: {
          keepShow: true,
          background: "#666"
        }
      },
      map: null,
      geoJSONGroup: null,
      stateStationGroup: null,
      taskGroup: null,
      taskArray: [],
      taskBackArray: [],
      taskId: null,
      taskData: {},
      beforeTaskImageArray: [],
      beforeTaskVideoArray: [],
      afterTaskImageArray: [],
      afterTaskVideoArray: [],
      taskTypeArray: [],
      taskInterval: null,
      searchCondition: "",
      stepArray: [
        { label: "待处理", value: 1 },
        { label: "待审核", value: 2 }
      ]
    };
  },
  methods: {
    init() {
      this.initSwiper();
      this.getTaskTypeList();
      this.getCityDistrict();
    },
    initSwiper() {
      new swiper("#psi-swiper-before", {
        grabCursor: true,
        observer: true, //修改swiper自己或子元素时，自动初始化swiper
        observeParents: true //修改swiper的父元素时，自动初始化swiper
      });
      new swiper("#psi-swiper-after", {
        grabCursor: true,
        observer: true, //修改swiper自己或子元素时，自动初始化swiper
        observeParents: true //修改swiper的父元素时，自动初始化swiper
      });
    },
    getTaskTypeList() {
      getTaskTypeList(data => {
        this.taskTypeArray = data;
      });
    },
    getCityDistrict() {
      getCityDistrict(data => {
        this.initMap(data);
        this.loadTileLayer();
        this.loadGeoJSON(data);
        getStateStationRealtime(data => {
          this.crateStateStationList(data);
        });
        this.getNewTaskList();

        this.intervalGetNewTaskList();
      });
    },
    initMap(data) {
      this.map = L.map("leaflet", {
        center: [data.lat, data.lng],
        zoom: 13
      });
    },
    loadTileLayer() {
      L.tileLayer(
        "http://t{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={z}&TileRow={y}&TileCol={x}&style=default&format=tiles&tk=bebf738d00ce5ce52058e5d1619d4f5c",
        {
          maxZoom: 18,
          minZoom: 9,
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          detectRetina: true
        }
      ).addTo(this.map);

      L.tileLayer(
        "https://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=bebf738d00ce5ce52058e5d1619d4f5c",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"]
        }
      ).addTo(this.map);
    },
    loadGeoJSON(data) {
      let __this = this;
      let layer = new L.geoJSON(JSON.parse(data.geojson), {
        coordsToLatLng: function(coords) {
          let wgs = __this.gps.gcj02ToWgs84(coords[1], coords[0]);
          return L.CRS.EPSG4326.unproject(L.point(wgs.lng, wgs.lat));
        },
        style: {
          fillColor: "transparent",
          color: "#ff0"
        }
      });
      this.geoJSONGroup = new L.LayerGroup();
      this.geoJSONGroup.addLayer(layer);
      this.geoJSONGroup.addTo(this.map);
    },
    crateStateStationList(data) {
      this.stateStationGroup = new L.LayerGroup();
      data.forEach(item => {
        this.createStateStation(item);
      });
      this.stateStationGroup.addTo(this.map);
    },
    createStateStation(data) {
      let latLng = new L.LatLng(data.latitude, data.longitude);

      let icon = L.icon({
        iconUrl: stateStationIcon,
        iconSize: [16, 16],
        iconAnchor: [8, 8]
      });
      let iconMarker = new L.marker(latLng, { icon: icon });
      this.stateStationGroup.addLayer(iconMarker);

      let address = L.divIcon({
        html: `<p>${data.station}</p>`,
        className: "address",
        iconSize: [80, 25],
        iconAnchor: [40, -15]
      });
      let addressMarker = new L.marker(latLng, { icon: address });
      this.stateStationGroup.addLayer(addressMarker);

      let array500 = this.gps.getCircleLatLng(
        data.latitude,
        data.longitude,
        0.5
      );
      let polygon500 = L.polygon(array500, {
        color: "#ff0000",
        weight: 2,
        opacity: 0.8,
        fillOpacity: 0
      });
      this.stateStationGroup.addLayer(polygon500);

      let array1000 = this.gps.getCircleLatLng(
        data.latitude,
        data.longitude,
        1.0
      );
      let polygon1000 = L.polygon(array1000, {
        color: "#ff9000",
        weight: 2,
        opacity: 0.8,
        fillOpacity: 0
      });
      this.stateStationGroup.addLayer(polygon1000);

      let array3000 = this.gps.getCircleLatLng(
        data.latitude,
        data.longitude,

        3.0
      );
      let polygon3000 = L.polygon(array3000, {
        color: "#ffc000",
        weight: 2,
        opacity: 0.8,
        fillOpacity: 0
      });
      this.stateStationGroup.addLayer(polygon3000);
    },
    getNewTaskList() {
      getNewTaskList(data => {
        if (this.validateArrayIsChange(data)) {
          this.taskBackArray = data;
          this.searchFunc();
          this.initPlyr();
        }
      });
    },
    validateArrayIsChange(data) {
      return !(data.toString() === this.taskBackArray.toString());
    },
    searchFunc() {
      this.taskArray = this.taskBackArray.filter(item => {
        let reg = new RegExp(this.searchCondition);
        return reg.test(item.address) || reg.test(item.content);
      });
      this.map.closePopup();
      if (this.taskGroup !== null) {
        this.map.removeLayer(this.taskGroup);
      }
      this.createMarkerList();

      this.taskId = this.getTaskId();
      this.taskSelected(this.taskId);
    },
    createMarkerList() {
      this.taskGroup = new L.LayerGroup();
      this.taskArray.forEach(item => {
        this.createTaskMarker(item);
      });
      this.taskGroup.addTo(this.map);
    },
    createTaskMarker(data) {
      let icon = L.divIcon({
        html: `<div class="container ${
          data.step === 1 ? "new" : "processed"
        }"></div>`,
        className: "circle",
        iconSize: [16, 16],
        iconAnchor: [8, 8]
      });
      let wgsLatLng = this.gps.bd09ToWgs84(data.lat, data.lng);
      let latLng = new L.LatLng(wgsLatLng.lat, wgsLatLng.lng);
      let marker = new L.marker(latLng, {
        icon: icon
      });
      marker.addEventListener("click", () => {
        this.taskId = data.id;
        this.taskSelected(this.taskId);
      });
      this.taskGroup.addLayer(marker);
    },
    taskSelected(taskId) {
      this.taskId = taskId;
      this.getTaskData(taskId);

      if (this.utils.validateIsNotEmpty(this.taskData)) {
        let wgs = this.gps.bd09ToWgs84(this.taskData.lat, this.taskData.lng);
        this.map.panTo([wgs.lat, wgs.lng]);
        this.createPopup(this.taskData);
      }
    },
    getTaskData() {
      this.beforeTaskImageArray = [];
      this.beforeTaskVideoArray = [];
      this.afterTaskImageArray = [];
      this.afterTaskVideoArray = [];
      if (this.taskId === null) {
        this.taskData = {};
      } else {
        this.taskData = this.taskArray.find(item => {
          return item.id === this.taskId;
        });
        if (this.taskData.taskProcessList.length > 0) {
          this.beforeTaskImageArray = this.taskData.taskProcessList[0].taskImageList;
          this.beforeTaskVideoArray = this.taskData.taskProcessList[0].taskVideoList;
        }
        if (this.taskData.taskProcessList.length > 1) {
          this.afterTaskImageArray = this.taskData.taskProcessList[1].taskImageList;
          this.afterTaskVideoArray = this.taskData.taskProcessList[1].taskVideoList;
        }
      }
    },
    createPopup() {
      if (this.utils.validateIsNotEmpty(this.taskData)) {
        let timestamp = new Date().getTime();
        let content = getNewTaskPopupTemplate(this.taskData, timestamp);
        let wgsLatLng = this.gps.bd09ToWgs84(
          this.taskData.lat,
          this.taskData.lng
        );
        let latLng = new L.LatLng(wgsLatLng.lat, wgsLatLng.lng);
        L.popup({
          offset: L.point(0, 8),
          maxWidth: 5760
        })
          .setLatLng(latLng)
          .setContent(content)
          .openOn(this.map);

        if (
          this.beforeTaskImageArray.length > 0 ||
          this.beforeTaskVideoArray.length > 0
        ) {
          new swiper("#before-task-swiper-" + timestamp, {
            grabCursor: true
          });

          plyr.setup(document.querySelectorAll(".before-task-leaflet-video"));
        }
        if (
          this.afterTaskImageArray.length > 0 ||
          this.afterTaskVideoArray.length > 0
        ) {
          new swiper("#after-task-swiper-" + timestamp, {
            grabCursor: true
          });

          plyr.setup(document.querySelectorAll(".after-task-leaflet-video"));
        }
      }
    },
    getTaskId() {
      if (this.taskArray.length === 0) {
        return null;
      }
      if (this.taskId === null) {
        return this.taskArray[0].id;
      }
      let inList = this.taskArray.some(item => {
        return item.id === this.taskId;
      });
      return inList ? this.taskId : this.taskArray[0].id;
    },
    initPlyr() {
      this.$nextTick(() => {
        plyr.setup(document.querySelectorAll(".psi-video"));
      });
    },
    intervalGetNewTaskList() {
      this.taskInterval = setInterval(() => {
        this.getNewTaskList(false);
      }, 5000);
    },
    formatterTaskType(type) {
      let typeObject = this.taskTypeArray.find(item => {
        return Number(item.id) === Number(type);
      });
      return typeObject ? typeObject.type : "";
    },
    formatterTaskStep(step) {
      let stepObject = this.stepArray.find(item => {
        return Number(item.value) === Number(step);
      });
      return stepObject ? stepObject.label : "";
    },
    formatterDistance(data) {
      if (this.utils.validateIsNotEmpty(data)) {
        let distance = data.distance;
        if (distance <= 500) {
          return "500米内";
        } else if (distance <= 1000) {
          return "1000米内";
        } else if (distance <= 3000) {
          return "3000米内";
        } else if (distance > 3000) {
          return "3000米外";
        }
      }
      return "";
    }
  },
  mounted() {
    this.init();
  },
  destroyed() {
    if (this.taskInterval) {
      clearInterval(this.taskInterval);
      this.taskInterval = null;
    }
  }
};
</script>

<style scoped lang="stylus">
#psi
  position relative
  width 100%
  height 100%

  > .row-1
    height 120px

  > .row-2
    height 894px

    > .col-1
      width 870px
      height 100%

      > .row-1
        height 59px
        padding 30px 0

      > .row-2
        height 775px

        #leaflet
          position relative
          top 0
          left 0
          width 100%
          height 100%

          >>> .leaflet-marker-icon.address
            > p
              position relative
              width 100%
              height 20px
              border 1px solid #000
              background-color #fff
              border-radius 5px
              text-align center
              line-height 20px
              font-size 12px
              color #000

          >>> .leaflet-marker-icon.circle
            > .container
              position relative
              width 16px
              height 16px
              border-radius 50%
              text-align center
              line-height 30px
              font-size 14px
              color #000
            > .container.new
              background-color #d76f00
            > .container.processed
              background-color #ddcb03


          >>> .leaflet-popup-content-wrapper
            color #000
            background-color rgba(0, 0, 0, 0.8)

            > .leaflet-popup-content
              position relative

              > .container
                position relative
                width 320px
                margin 0 auto
                color #fff

                > .row-1
                  line-height 33px
                  font-size 16px

                > .row-2, > .row-3
                  width 320px

                  > .row-1
                    p
                      position relative
                      height 24px
                      padding-left 15px
                      margin 10px 0
                      line-height 24px
                      font-size 16px
                      color #FFF

                    p::before
                      content ''
                      display block
                      position absolute
                      left 0
                      top 0
                      width 5px
                      height 100%
                      background-color #00b2ff

                  > .row-2
                    height 180px
                    > .swiper-container
                      height 100%
                      > .swiper-wrapper
                        height 100%
                        > .swiper-slide
                          height 100%
                          background-color #000

                          > .table
                            display table
                            width 100%
                            height 100%
                            margin 0 auto

                            > .cell
                              display table-cell
                              vertical-align middle
                              max-width 100%
                              max-height 100%

                              > img
                                display block
                                max-width 180px
                                max-height 180px
                                margin 0 auto

                          > video
                            width 100%
                            height 100%
                            border none
                            outline none

          >>> .leaflet-popup-tip-container
            > .leaflet-popup-tip
              background-color rgba(0, 0, 0, 0.8)

    > .col-2
      width 1000px
      height 100%

      >.row-1
        height 119px

      > .row-2
        height 775px
        background-color #041845

        > .row-1
          height 33px
          padding 37px 15px 37px 30px

          > .col-1
            width 500px

            > p
              position relative
              padding-left 38px
              line-height 33px
              font-size 28px
              color #fff

            > p::before
              content ''
              position absolute
              top 0
              left 0
              width 33px
              height 33px
              background url("../../assets/img/20190718140035.png") no-repeat top left
              background-size 33px 33px

          > .col-2
            width 455px

            > .row
              padding 0 30px 0 15px

              > .row
                height 33px

                > .col-1
                  width 338px

                  > input
                    width 258px
                    height 29px
                    float right
                    padding 1px 10px
                    border 1px solid #00a0e9
                    outline 0
                    background-color #022776
                    font-size 18px
                    color #fff

                > .col-2
                  width 72px

                  > .button
                    width 72px
                    height 33px
                    background-color #00a0e9
                    cursor pointer

                  > .button::after
                    content ''
                    position absolute
                    top 7px
                    left 27px
                    width 18px
                    height 19px
                    background url("../../assets/img/station/20190718140042.png") no-repeat top left
                    background-size 18px 19px

        > .row-2
          height 640px

          > .row
            padding-left 30px
            height 100%

            >>>.__panel
              > .__view
                > .row
                  height 150px

                  > .row-1
                    height 100px

                    > .col-1
                      width 545px
                      height 70px
                      padding 15px

                      > .table
                        display table
                        width 100%
                        height 100%
                        margin 0 auto

                        > .cell
                          display table-cell
                          vertical-align middle

                          > p
                            max-height 70px
                            line-height 35px
                            white-space normal
                            overflow hidden
                            text-overflow ellipsis
                            display -webkit-box  //弹性盒模型
                            -webkit-box-orient vertical  //上下垂直
                            -webkit-line-clamp 4  //自定义行数
                            font-size 24px
                            color #fff

                            > span
                              display -webkit-box
                              -webkit-line-clamp 2
                              -webkit-box-orient vertical
                              overflow hidden
                              text-overflow ellipsis

                    > .col-2
                      width 390px
                      height 100%

                      > .row
                        width 100%
                        height 100%

                        > .col
                          width 130px
                          height 70px
                          float right

                          > p
                            display block
                            width 120px
                            height 40px
                            margin 30px auto
                            background-color #1470c2
                            border-radius 10px
                            line-height 40px
                            text-align center
                            font-size 20px
                            color #fff

                          > p.new
                            background-color #d76f00

                          > p.processed
                            background-color #ddcb03

                  > .row-2
                    height 50px
                    line-height 50px

                    > .col-1
                      width 545px
                      height 100%

                      > p
                        font-size 20px
                        color #80a7fc
                        padding-left 50px

                      > p::before
                        content ''
                        display block
                        position absolute
                        top 12px
                        left 20px
                        width 19px
                        height 27px
                        background url("../../assets/img/20200420153452.png") no-repeat top left
                        background-size 19px 27px

                    > .col-2
                      width 390px
                      height 100%
                      padding 0 10px

                      > p
                        text-align right
                        font-size 20px
                        color #80a7fc

                > .row::after
                  position absolute
                  bottom 0
                  left 0
                  width 100%
                  height 1px
                  background-color #80a7fc

                > .row.active
                  background-color #030e26
    > .col-3
      width 1500px
      > .row-1
        height 59px
        padding 30px 0

      > .row-2
        height 775px
        background-color #030e26

        > .col-1
          width 500px
          height 100%
          padding 0 30px

          >.row-1
            padding 30px 0 10px
            min-height 80px

            > .row-1
              > p
                line-height 40px
                text-align justify
                word-wrap break-word
                word-break break-all
                white-space normal
                font-size 28px
                color #fff

            > .row-2
              padding 10px 0

              > .row-1
                > p
                  line-height 40px
                  font-size 20px
                  color #80a7fc
                  padding-left 30px

                > p::before
                  content ''
                  display block
                  position absolute
                  top 12px
                  left 0
                  width 19px
                  height 27px
                  background url("../../assets/img/20200420153452.png") no-repeat top left
                  background-size 19px 27px

              > .row-2
                line-height 40px

                > p
                  font-size 20px
                  color #80a7fc

          > .row-2
            > .row
              p
                line-height 50px
                font-size 22px
                color #FFF

        > .col-2, > .col-3
          width 410px
          margin 0 auto
          padding 0 30px

          > .row-1
            width 100%
            padding 30px 0

            > p
              position relative
              height 24px
              padding-left 15px
              margin 10px 0
              line-height 24px
              font-size 22px
              color #FFF

            p::before
              content ''
              display block
              position absolute
              left 0
              top 0
              width 5px
              height 100%
              background-color #00b2ff

          > .row-2
            width 410px
            height 640px
            margin 0 auto

            > .swiper-container
              height 100%

              > .swiper-wrapper
                height 100%

                > .swiper-slide
                  height 100%
                  background-color #000

                  > .table
                    display table
                    width 100%
                    height 100%
                    margin 0 auto

                    > .cell
                      display table-cell
                      vertical-align middle
                      max-height 100%

                      > img
                        display block
                        max-width 720px
                        max-height 640px
                        margin 0 auto

                  > video
                    width 100%
                    height 100%
</style>
